define(function(require){
    var main =require('/static/main.js');
    require('/static/ajaxfileupload.js');
    require('/modules/js/cropbox.js');
    var m = new main();
    var sales = {
        AdvertorialId : $_GET['advertorialid'],
        islook : $_GET['islook'],
        adid :3,
        ImgSrc :'',
        chosetagList:[],
        tagList:[],
        projectindex:2,
        _init:function(){
            // 初始化左边菜单
            this.bindEvent();
            this.cropperImg();
            this.simditor();
            this.ajaxUpload();
            this.getSignList();
            if(sales.AdvertorialId){
                this.getInitDataGet();
            }else{
                this.datetime(1);
                this.timeslot(1,1);
                $(".q-cont-all").fadeIn();
            }

        },
        getInitDataGet:function(){
            $.ajax({
                type: "POST",
                url: "/promote/ad-template-get",
                data : {AdvertorialId:sales.AdvertorialId},
                dataType: "json",
                success: function (ret){
                    if(ret.IsBizSuccess){
                        if(ret.AdvertorialStatus == 100 || sales.islook){
                            $("#InputMessage").next().remove();
                            $("#InputMessage").remove();
                            $("#ShowMessage").removeClass("fl").find(".q-show-ret ").css("margin",'0 auto');
                        }
                        var data = ret.Model;
                        $("#ShowMessage .MainSrc").attr("src",data.MainSrc);
                        var Imgsrc =  data.MainSrc;
                        sales.ImgSrc = sales.GetUrlRelativePath(Imgsrc);
                        sales.setVal(data.Title,'Title');
                        sales.setVal(data.AdDescribe,'AdDescribe');
                        sales.setVal(data.ShopName,'ShopName');
                        sales.setVal(data.ShopAdd,'ShopAdd');
                        sales.setVal(data.ShopPhone,'ShopPhone');
                        $(".promote-style-call").attr("href",'tel:'+data.ShopPhone);
                        sales.editor.setValue(data.Notice);
                        sales.setCont(data.AdContent);
                        if(!data.IsCountLimit){
                            $(".AppointmentSetCount").click();
                        }
                        if(!data.IsShowByImg){
                            $(".AppointmentSetImg").click();
                            $(".ShowText").show();
                            $(".ShowImg").hide();
                        }
                        if(!data.IsTimeLimit){
                            $(".AppointmentSetTime").click();
                        }
                        //日期
                        $(".ActStartTime").html('<span class="ion-ios7-clock"></span>'+m.formatYmdtext(data.StartDate)+'至'+m.formatYmdtext(data.EndDate));
                        sales.setSubscribe(data.AdSubscribeItemList,data.IsCountLimit,data.IsShowByImg,data.IsTimeLimit);
                        $(".q-cont-all").fadeIn();

                        //tagList
                        if(ret.TagList.length > 0){
                            var tagstr = '';
                            $.each(ret.TagList,function(k,v){
                                tagstr+='<li class="chose_li"  data-id="'+v.TagId+'">'+v.TagName+'<span class="ion-close-round"></span></li>'
                            });
                            $(".tag-item").html(tagstr);
                            sales.chosetagList = ret.TagList;
                            sales.setTags();
                        }
                    }
                }
            });
        },
        loadedindex:1,
        owl:'',
        loaded:function(){
            sales.loadedindex ++;
            var index  = $(".project-list-list").find(".active").index();
            $(".owl-example-list").find(".item").eq(index).addClass("active");
            var str  = '<div id="owl-example'+sales.loadedindex+'" class="owl-carousel">'+$(".owl-example-list").html()+'</div>';
            $(".ShowImg").html(str);
           sales.owl = $("#owl-example"+sales.loadedindex);
            sales.owl.owlCarousel({
                items:2,
                pagination:false,
                responsive:false,
            });
            sales.owl.trigger('owl.goTo', index)

        },
        getSignList:function(){
            $.ajax({
                type: "POST",
                url: "/customer/sign-list",
                dataType: "json",
                success: function (ret) {
                    var str = '';
                    if(ret.Models.length > 0){
                        $.each(ret.Models,function(k,v){
                            str+='<span class="Label_btnspan" data-id="'+v.TagId+'" data-name="'+v.TagName+'">'+v.TagName+'</span>'
                        });
                        sales.tagList = ret.Models;
                        sales.setTags();
                    }else{
                        $('.Label_btn').css({'text-align':'center'})
                        str+='暂无标签'
                    }
                    $('.Label_btn').html(str);
                }
            });

        },
        setTags:function(){
            if(sales.tagList.length > 0 && sales.chosetagList.length > 0){
                $.each(sales.tagList,function(k,v){
                    $.each(sales.chosetagList,function(key,val){
                        if(v.TagId == val.TagId){
                            $(".Label_btn").find(".Label_btnspan").eq(k).addClass("E8ECEE")
                        }
                    })
                })
            }
        },
        bindEvent:function(){
            //内容框输入
            $('.p-yl2').keyup(function (e) {
                var className = $(this).data("classname"); $("#ShowMessage ."+className).text($(this).val());
            });
            //手机号输入
            $('.ShopPhone').keyup(function (e) {
                $(".promote-style-call").attr("href",'tel:'+ $(this).val());
            });

            //价格
            $(document).on("change", ".p-yl4", function(){
                var reg = $(this).val().match(/\d+(\.\d{1,2})?/);
                var txt = '';
                if (reg != null)
                {
                    txt = reg[0];
                }
                $(this).val(txt);
                var className = $(this).data("classname");
                var pricetype = $(this).data("type");
                if(className == 'Price'){
                    var type =  $("input[name='admarkettype']:checked").val();
                    if(type == 200 && pricetype == 100){
                        return false;
                    }
                }
                $("#ShowMessage ."+className).text(txt);
            });

            //添加图片
            $(document).on("click", ".add-img", function(){
                var str  = sales.addStr('img');
                $(this).closest(".form-group").after(str[0]);
                var adid = $(this).attr("data-adid");
                $(".promote-cont"+adid).after(str[1]);
            });
            //添加文字说明
            $(document).on("click", ".add-font", function(){
                var str  = sales.addStr('font');
                $(this).closest(".form-group").after(str[0]);
                var adid = $(this).attr("data-adid");
                $(".promote-cont"+adid).after(str[1]);

            });
            //添加段落
            $(document).on("click", ".promote-addgrapeach ", function(){
                var str  = ' <div class="promote-grapeach">';
                var fontsrt = sales.addStr('font');
                var imgstr = sales.addStr('img');
                str  += fontsrt[0]+imgstr[0];
                str  += '</div>';
                $(".promote-scendcon").append(str);
                $(".promote-adcontent-item").append(fontsrt[1]+imgstr[1]);
            });
            //删除
            $(document).on("click", ".del-btn", function(){
                var adid = $(this).attr("data-adid");
                $(this).closest(".form-group").remove();
                $(".promote-cont"+adid).remove();
            });
            $(document).on("keyup", ".p-yl3", function(){
                var adid = $(this).attr("data-adid");
                $(".promote-cont"+adid).text($(this).val());
            });


            // 点击选择标签
            $(document).on('click','.Label_btn span',function(){
                if($(this).hasClass('E8ECEE')){
                    $(this).removeClass('E8ECEE')
                }else{
                    $(this).addClass('E8ECEE')
                }
            })
            //删除标签
            $(document).on('click','.chose_li',function(){
                var id = $(this).attr("data-id");
                $(".Label_btn").find(".Label_btnspan").each(function(){
                    var tagid = $(this).attr("data-id");
                    $(this).removeClass('E8ECEE');
                    if(parseInt(id) == parseInt(tagid)){
                        $(this).removeClass('E8ECEE');
                    }
                });
                $(this).remove();
            })
            // 选择完成
            $('.choseOk').click(function(){
                var str = '';
                $('.Label_btnspan.E8ECEE').each(function(k,v){
                    var id = $(this).data('id');
                    var name = $(this).data('name');
                    str +='<li class="chose_li"  data-id="'+id+'">'+name+'<span class="ion-close-round"></span></li>';
                })
                $(".tag-item").html(str);
                $('#TagList').modal('hide');
            });
            //保存
            $(document).on("click", ".SaveBtn", function(){
                sales.ActivitySave(false);
            });
            //发布
            $(document).on("click", ".PublishBtn", function(){
                sales.ActivitySave(true);
            });
            /* 预约 start */

            //预约时间限制
            $(document).on("change", ".AppointmentSetTime", function(){
                var ischecked = $(this).is(":checked");
                if(!ischecked){
                    $(".appsettime").addClass('hiden');
                    var sibchecked = $(this).parent().parent().next().next().find("input").is(":checked");
                    if(!sibchecked){
                        $(".AppointmentSet").hide();
                    }else{
                        $(".AppointmentSet").show();
                    }
                    $(".manage_per .time").hide();
                    $(".time-list").hide();
                    $(".AppointmentTime").addClass("hidden1");
                }else{
                    $(".appsettime").removeClass('hiden');
                    $(".AppointmentTime").removeClass("hidden1");
                    $(".AppointmentSet").show();
                    $(".manage_per .time").show();
                    $(".time-list").show();
                }
            });
            //预约数量限制
            $(document).on("change", ".AppointmentSetCount", function(){
                var ischecked = $(this).is(":checked");
                if(!ischecked){
                    var sibchecked = $(this).parent().parent().prev().prev().find("input").is(":checked");
                    if(!sibchecked){
                        $(".AppointmentSet").hide();
                    }else{
                        $(".AppointmentSet").show();
                    }
                    $(".AppointmentCount").addClass("hidden1");
                }else{
                    $(".AppointmentCount").removeClass("hidden1");
                    $(".AppointmentSet").show();
                }
            });
            //预约数量限制
            $(document).on("change", ".AppointmentSetImg", function(){
                var ischecked = $(this).is(":checked");
                if(!ischecked){
                    $(".AppointmentImg").hide();
                    $(".ShowText").show();
                    $(".ShowImg").hide();
                }else{
                    $(".AppointmentImg").show();
                    $(".ShowText").hide();
                    $(".ShowImg").show();
                }
            });
            //预约对象类型
            $(document).on("change", ".SubscribeObj", function(){
                var value = $(this).val();
                if($(this).val() == 1){
                   $(this).closest(".form-group ").next().find(".ObjName").html("项目名称：");
                    //$("#ShowMessage .SubscribeObj").html('项目');
                }else{
                    //$(".ObjName").html("人员名称：");
                    $(this).closest(".form-group ").next().find(".ObjName").html("人员名称：");
                    //$("#ShowMessage .SubscribeObj").html('人员');
                }
            });

            $(document).on("click", ".project-list .add", function(){
                //添加预约项目
                $(".delProject").show();
                var projectindex =  sales.projectindex;
                //var SubscribeObj = $("input[name='SubscribeObj']:checked").val();
                var SetTime = !$(".AppointmentSetTime").is(":checked");
                var SetCount = !$(".AppointmentSetCount").is(":checked");
                var SetImg = $(".AppointmentSetImg").is(":checked");

                var str  = '<li class="project-item active"><span>'+projectindex+'</span></li>';
                $(".project-list-list").append(str);
                $(".project-list-list .project-item").eq($(".project-list-list .project-item").length-1).siblings().removeClass("active");
                var contstr = '<div class="projectcont-item">\
                     <div class="form-group overflow">\
                    <label class="col-md-2 control-label padleft17" style="font-weight: 500;">预约设置：</label>\
                    <div class="col-md-7">\
                        <div class="m-t-10">\
                            <label class="cr-styled"><input type="radio" name="project-type'+projectindex+'" checked class="SubscribeObj" value="1"><i class="fa"></i> 预约项目</label>\
                                <label class="cr-styled m-l-20"><input type="radio"  name="project-type'+projectindex+'" class="SubscribeObj" value="2"><i class="fa"></i> 预约人员</label>\
                                </div>\
                            </div>\
                            <label class="col-md-3 control-label pass-msg error notice" style="font-weight: 500;"></label>\
                        </div><div class="form-group overflow">\
                <label class="col-md-2 control-label padleft17 ObjName" style="font-weight: 500;">项目名称：</label>\
                <div class="col-md-3">\
                <input type="text" class="form-control p-yl6 objname" data-pid="'+projectindex+'" placeholder="">\
                </div>\
                <div class="col-md-4">\
                <div class="input-group AppointmentImg" style="display: '+(SetImg ? '':'none')+'">\
                    <input type="text" id="example-input2-group1" name="example-input2-group1" class="form-control profileupload" data-pid="'+projectindex+'" readonly="">\
                        <span class="input-group-addon"><i class="fa ion-image"></i></span>\
                    </div>\
                </div>\
                <label class="col-md-3 control-label pass-msg error notice" style="font-weight: 500;"></label>\
                </div>\
                <div class="form-group overflow">\
                <label class="col-md-2 control-label padleft17" style="font-weight: 500;">预约日期：</label>\
                <div class="col-md-3">\
                <div class="input-group">\
                    <input type="text" class="form-control startdate" placeholder="" id="StartDate'+projectindex+'" readonly="">\
                        <span class="input-group-addon"><i class="glyphicon ion-calendar"></i></span>\
                    </div>\
                </div>\
                <div class="col-md-1" style="text-align: center;height: 33px;line-height: 33px;">至</div>\
                <div class="col-md-3">\
                    <div class="input-group">\
                        <input type="text" class="form-control enddate" placeholder="" id="EndDate'+projectindex+'" readonly="">\
                            <span class="input-group-addon"><i class="glyphicon ion-calendar"></i></span>\
                        </div>\
                    </div>\
                    <label class="col-md-3 control-label pass-msg error usedate" style="font-weight: 500;"></label>\
                </div>\
                <div class="appsettime '+(SetTime ? 'hiden' :'')+'"><div class="form-group overflow AppointmentSet " style="display: '+(SetTime && SetCount ? 'none':'block') +'">\
                <label class="col-md-2 control-label padleft17 AppointmentTime '+(SetTime ? 'hidden1' :'')+'" style="font-weight: 500;"><span>时间1：</span></label>\
                <div class="col-md-3 AppointmentTime '+(SetTime ? 'hidden1' :'')+'">\
                <input type="text" class="form-control subscribetime" id="StartTime'+projectindex+'-1">\
                </div>\
                <div class="col-md-1 AppointmentCount '+(SetCount ? 'hidden1' :'')+'" style="text-align: center;height: 33px;line-height: 33px;padding: 0px;"><span >数量</span></div>\
                <div class="col-md-3 AppointmentCount '+(SetCount ? 'hidden1' :'')+'" >\
                    <input type="number" class="form-control p-yl4 count" data-classname="count" >\
                    </div>\
                    <div class="col-md-3 control-label" style="font-weight: 500;">\
                        <p class="addTime"><i class="ion-plus"></i></p>\
                    </div>\
                </div>\
                </div></div>';
                $(".projectcont-list").append(contstr);
                $(".projectcont-list .projectcont-item").eq($(".projectcont-list .projectcont-item").length-1).siblings().hide();
                sales.datetime(projectindex);
                sales.timeslot(projectindex,1);
                //showtext
                var textstr = '<li class="name active promote-protext'+projectindex+'">预约项目'+projectindex+'</li>';
                $(".show-text-list").append(textstr);
                $(".show-text-list .name").eq( $(".show-text-list .name").length-1).siblings().removeClass("active");

                //showimg
                var imgstr = ' <div class="item active appa-list-item">\
                    <p class="img promote-proimg'+projectindex+'">\
                <img src="/modules/img/default.jpg"></p>\
                <p class="name onetexthide  promote-protext'+projectindex+'">预约项目'+projectindex+'</p>\
                </div>';
                $(".owl-example-list").append(imgstr);
                $(".owl-example-list .item").eq($(".owl-example-list .item").length-1).siblings().removeClass("active");
                sales.loaded();
                var timestr = '<div class="date-list-item">\
                    <div class="date-time">\
                <div class="buylen manage_per" style="margin-bottom: 0px;">\
                    <ul>\
                        <li class="handhover date">\
                            <p class="left">预约日期</p>\
                          <p class="right" style="position: relative;">\
                              <span class="StartDate'+projectindex+'">2017年07月19日</span>至<span class="EndDate'+projectindex+'">2017年07月28日</span>\
                                <span class="fa fa-angle-right" style="font-size: 22px;color: #7b7b7b;"></span>\
                          </p>\
                        </li>\
                        <li class="handhover time" style="display:'+(SetTime ? 'none':'')+'">\
                            <p class="left">预约时间</p>\
                            <p class="right"></p>\
                        </li>\
                    </ul>\
                </div>\
                </div>\
                <div class="time-list pad4" style="display:'+(SetTime ? 'none':'')+'">\
                    <span class="time-items"> </span>\
                </div>\
                </div>';
                $(".date-list-wrap").append(timestr);
                $(".date-list-wrap .date-list-item").eq($(".date-list-wrap .date-list-item").length-1).show().siblings().hide();
                sales.projectindex++;
            });



            //添加预约时间和数量
            $(document).on("click", ".addTime", function(){
                var SetTime = !$(".AppointmentSetTime").is(":checked");
                var SetCount = !$(".AppointmentSetCount").is(":checked");
                var i = $(this).closest(".projectcont-item").index();
                var j = $(this).closest(".AppointmentSet").index();
               var str = '<div class="form-group overflow AppointmentSet " style="display: '+(SetTime && SetCount ? 'none':'block') +'">\
                <label class="col-md-2 control-label padleft17 AppointmentTime '+(SetTime ? 'hidden1' :'')+'" style="font-weight: 500;"><span>时间'+(j+2)+'：</span></label>\
                <div class="col-md-3 AppointmentTime '+(SetTime ? 'hidden1' :'')+'">\
                <input type="text" class="form-control subscribetime" id="StartTime'+(i+1)+'-'+(j+2)+'">\
                </div>\
                <div class="col-md-1 AppointmentCount '+(SetCount ? 'hidden1' :'')+'" style="text-align: center;height: 33px;line-height: 33px;padding: 0px;"><span>数量</span></div>\
                <div class="col-md-3 AppointmentCount '+(SetCount ? 'hidden1' :'')+'">\
                    <input type="number" class="form-control p-yl4 count" data-classname="count">\
                    </div>\
                    <div class="col-md-3 control-label" style="font-weight: 500;">\
                        <p class="addTime"><i class="ion-plus"></i></p>\
                        <p class="DelTime"><i class="fa fa-trash-o"></i></p>\
                    </div>\
                </div>';
                $(this).closest(".appsettime").append(str);

                sales.timeslot(i+1,j+2);
                var timestr = '<span class="time-items"> </span>';
                $(".time-list").eq(i).find(".time-items").eq(j).after(timestr);

            });

            //删除预约数量
            $(document).on("click", ".DelTime", function(){
                var i = $(this).closest(".projectcont-item").index();
                var j = $(this).closest(".AppointmentSet").index();
                $(".date-list-wrap").find(".date-list-item").eq(i).find(".time-items").eq(j).remove();
                $(this).closest(".AppointmentSet").remove();

            });
            //选择预约项目
            $(document).on("click", ".project-list-list .project-item", function(){
               var index = $(this).index();
                $(this).addClass("active").siblings().removeClass("active");
                $(".projectcont-list .projectcont-item").eq(index).show().siblings().hide();
                $(".show-text-list li").eq(index).addClass("active").siblings().removeClass("active");
                $(".owl-wrapper .owl-item").eq(index).find(".item").addClass("active").parent().siblings().find(".item").removeClass("active");
                $(".date-list-wrap .date-list-item").eq(index).show().siblings().hide();
                if(sales.owl){
                    sales.owl.trigger('owl.goTo', index);
                }
            });

            /*输入参数*/
            //预约名称
            $(document).on("keyup", ".p-yl6", function(){
                var html =  $(this).val();
                var pid = $(this).attr("data-pid");

                $(".show-text-list").find(".promote-protext"+pid).text(html);
                $(".ShowImg").find(".promote-protext"+pid).text(html);
                $(".owl-example-list").find(".promote-protext"+pid).text(html);

            });


            //删除预约项目
            //$(".ShowText").show();
            //$(".owl-example-list").show();
            $(document).on("click", ".delProject", function(){
                var length = $(".project-list-list").find(".project-item").length;
                if(length > 1){
                    var index = $(".project-list-list .acitve").index();
                    $(".project-list-list").find(".project-item").eq(index).remove();
                    $(".projectcont-list").find(".projectcont-item").eq(index).remove();
                    $(".project-list-list").find(".project-item").eq(0).click();
                    $(".show-text-list").find(".name").eq(index).remove();
                    $(".owl-example-list").find(".item").eq(index).remove();
                    if(length > 2){
                        sales.loaded();
                    }else{
                        var str = '<div id="owl-example" class="owl-carousel">'+$(".owl-example-list").html()+'</div>';
                        $(".ShowImg").html(str);
                        $(".ShowImg").find(".item").eq(0).addClass("active");
                    }
                }

            });

            /* 预约 end */


        },
        isactive:false,
        ActivitySave:function(IsPublish){
            if(sales.isactive){
                return false;
            }
            var ImgSrc  = sales.ImgSrc.trim();
            var ImgArray = ImgSrc.substring(0,1);
            if(ImgArray == '/'){
                sales.ImgSrc =ImgSrc.substring(1);
            }
            var JsonData = {
                MainSrc : sales.ImgSrc ,
                Title :$("#InputMessage .Title").val().trim(),
                AdDescribe :$("#InputMessage .AdDescribe").val().trim(),
                ShopName :$("#InputMessage .ShopName").val().trim(),
                ShopAdd :$("#InputMessage .ShopAdd").val().trim(),
                ShopPhone :$("#InputMessage .ShopPhone").val().trim(),
                Notice :sales.editor.getValue(),
                AdContent :sales.getCont(),
                TemplateType:100,
                IsTimeLimit:$(".AppointmentSetTime").is(":checked"),
                IsCountLimit:$(".AppointmentSetCount").is(":checked"),
                IsShowByImg:$(".AppointmentSetImg").is(":checked"),
                SubscribeObj:$("input[name='SubscribeObj']:checked").val()
            }
            var ItemList = [];
            $(".projectcont-list .projectcont-item").each(function(){
                var data = {};
                var type = $(this).find("input[type='radio']:checked").val();
                data.SubscribeType = type== 1 ? 200 :100;
                data.StartDate = $(this).find(".startdate").val();
                data.EndDate = $(this).find(".enddate").val();
                data.SubscribeObjName  = $(this).find(".objname").val().trim();
                if(JsonData.IsShowByImg){
                    var img = $(this).find(".profileupload").val().trim();
                    var ImgArr = img.substring(0,1);
                    if(ImgArr == '/'){
                        img = img.substring(1);
                    }
                    data.SubscribeObjSrc  = img;
                }

                var tiemdatelist = [];
                $(this).find(".appsettime").find(".form-group").each(function () {
                    //限定时间和数量
                    var tiemdateitem = {};
                    if (JsonData.IsTimeLimit) {
                        tiemdateitem.SubscribeTime = $(this).find(".subscribetime").val();
                        if( JsonData.IsCountLimit){
                            tiemdateitem.SubscribeCount = $(this).find(".count").val();
                        }
                        tiemdatelist.push(tiemdateitem);
                    }
                    //限定数量 不限定时间
                    if (!JsonData.IsTimeLimit && JsonData.IsCountLimit) {
                        data.SubscribeCount = $(this).find(".count").eq(0).val();
                    }

                });
                if (JsonData.IsTimeLimit) {
                    data.AdSubscribeTimeList = tiemdatelist;
                }
                ItemList.push(data);
            });
            JsonData.AdSubscribeItemList = ItemList;
            //console.log(JsonData);
            //return false;
            var alltrue = true;
            var truearrya = [];
            truearrya.push(sales.errorMessage(JsonData.MainSrc,'mainsrc','请添加商品主图'));
            truearrya.push(sales.errorMessage(JsonData.Title,'title','请添加标题'));
            truearrya.push(sales.errorMessage(JsonData.AdDescribe,'addescribe','请添加商品名称'));
            //truearrya.push(sales.errorMessage(JsonData.ShopName,'shopname','请添加商户名称'));
            truearrya.push(sales.errorMessage(JsonData.ShopAdd,'shopadd','请添加商户地址'));
            truearrya.push(sales.errorMessage(JsonData.ShopPhone,'shopphone','请添加联系方式'));
            truearrya.push(sales.errorMessage(JsonData.Notice,'notice','请添加预约须知'));
            truearrya.push(sales.errorMessage(JsonData.AdContent,'adcontent','请添加详情说明'));
            var projectlist = [];
            $.each(JsonData.AdSubscribeItemList,function(k,v){
                projectlist[k] = true;
                if(v.SubscribeObjName.length < 1){
                    projectlist[k] = false;
                }
                if(JsonData.IsShowByImg  &&  v.SubscribeObjSrc.length < 1){
                    projectlist[k] = false;
                }
                if(v.StartDate.length < 1 || v.EndDate.length < 1){
                    projectlist[k] = false;
                }
                if(JsonData.IsTimeLimit){
                    $.each(v.AdSubscribeTimeList,function(key,val){
                        if(val.SubscribeTime.length < 1){
                            projectlist[k] = false;
                        }
                        if(JsonData.IsCountLimit && val.SubscribeCount.length < 1){
                            projectlist[k] = false;
                        }
                    });
                }else{
                    if(JsonData.IsCountLimit && v.SubscribeCount.length < 1){
                        projectlist[k] = false;
                    }
                }

            });
            var str  = '';
            $.each(projectlist,function(k,v){
               if(!v){
                   var index  = $(".project-list-list .project-item").eq(k).find("span").html();
                   if(str.length > 0){
                       str +='、预约项目'+(index);
                   }else{
                       str +='预约项目'+(index);
                   }
               }
            });
            if(str.length > 0){
                $(".pass-msg.project").html('请完善'+str+'的信息');
                truearrya.push(false);
            }else{
                $(".pass-msg.project").html('');
            }
            $.each(truearrya,function(k,v){
                if(v == false){
                    alltrue = false;
                    return false;
                }
            });
            var tagList = [];
            $(".tag-item").find(".chose_li").each(function(){
                tagList.push($(this).attr("data-id"));
            });
            if(tagList.length > 0){
                JsonData.TagIds = tagList;
            }
            if(alltrue){
                JsonData.AdvertorialId = sales.AdvertorialId;
                sales.isactive = true;
                $.ajax({
                    type: "POST",
                    url: "/promote/ad-subscribe-create",
                    data :JsonData,
                    dataType: "json",
                    success: function (ret){
                        if(ret.IsBizSuccess){
                            if(IsPublish){
                                //发布
                                $.ajax({
                                    type: "POST",
                                    url: "/promote/ad-publish",
                                    data :{AdvertorialId:ret.AdvertorialId},
                                    dataType: "json",
                                    success: function (ret){
                                        sales.isactive = false;
                                        if(ret.IsBizSuccess){
                                            layer.msg("发布成功");
                                            setTimeout(function(){
                                                window.location.href = "/promote/mypromote";
                                            },1500);
                                        }else{
                                            layer.msg("发布失败");
                                        }
                                    }
                                });
                            }else{
                                sales.isactive = false;
                                layer.msg("保存成功");
                                setTimeout(function(){
                                    window.location.href = "/promote/mypromote";
                                },1500);
                            }
                        }else{
                            sales.isactive = false;
                            if(IsPublish){
                                layer.msg("发布失败");
                            }else{
                                layer.msg("保存失败");
                            }

                        }

                    }
                });
            }
        },
        setVal:function(data,classname){
            $("#ShowMessage ."+classname).text(data);
            $("#InputMessage ."+classname).val(data);
        },
        setCont:function(AdContent){
            $(".promote-adcontent-item").html(AdContent);
            var str = '<div class="promote-grapeach">';
            var i = 0;
            $(AdContent).each(function(){
                var classname = $(this).attr("class");
                classname = parseInt(classname.split("promote-cont")[1]);
                i = classname > i ?classname : i;
                if($(this).find("img").length){
                    var imgsrc = $(this).find("img").attr("src");
                    str += '<div class="form-group overflow">\
                <label class="col-md-2 control-label padleft17" style="font-weight: 500;">展示图片：</label>\
                <div class="col-md-7 promote-chosetupload">\
                        <div class="input-group">\
                            <input type="text" id="example-input2-group1" name="example-input2-group1" class="form-control fileupload"  data-adid="'+classname+'" readonly="" value="'+imgsrc+'">\
                                <span class="input-group-addon"><i class="fa ion-image"></i></span>\
                            </div>\
                        </div>\
                        <div class="col-md-3 add-promote-btnlist">\
                            <ul class="p-ul5 p-ul7">\
                                <li class="add-img"  data-adid="'+classname+'"><span class="ion-image"></span></li>\
                                <li class="add-font" data-adid="'+classname+'"><span class="fa fa-font" style="font-size: 23px;"></span></li>\
                                <li class="del-btn"  data-adid="'+classname+'"><span class="fa fa-trash-o"></span></li>\
                                <div class="clear"></div>\
                            </ul>\
                        </div>\
                    </div>';
                }else{
                    var html  = $(this).html();
                    str += '<div class="form-group overflow">\
                    <label class="col-md-2 control-label padleft17" style="font-weight: 500;">文字说明：</label>\
                    <div class="col-md-7">\
                        <textarea class="form-control p-yl3"  data-adid="' + classname + '">'+html+'</textarea>\
                    </div>\
                    <div class="col-md-3 add-promote-btnlist">\
                        <ul class="p-ul5 p-ul7">\
                            <li class="add-img" data-adid="' + classname + '"><span class="ion-image"></span></li>\
                            <li class="add-font" data-adid="' + classname + '"><span class="fa fa-font" style="font-size: 23px;"></span></li>\
                            <li class="del-btn"   data-adid="' + classname + '"><span class="fa fa-trash-o"></span></li>\
                            <div class="clear"></div>\
                        </ul>\
                    </div>\
                </div>';
                }
            });
            str  += '</div>';
            sales.adid = i+2;
            $(".promote-scendcon").html(str);

        },
        setSubscribe:function(data,iscount,isimg,istime){
            var inputstr = '';
            var numberstr = '';
            var timestr = '';
            var textstr  = '';
            var imgstr = '';
            $.each(data,function(k,v){
                inputstr +='<div class="projectcont-item" style="display: '+ (k == 0 ? '': 'none')+'">\
                <div class="form-group overflow">\
                <label class="col-md-2 control-label padleft17" style="font-weight: 500;">预约设置：</label>\
                <div class="col-md-7">\
                <div class="m-t-10">\
                    <label class="cr-styled"><input type="radio" name="project-type'+k+'" '+(v.SubscribeType == 200 ? 'checked':'')+' class="SubscribeObj" value="1"><i class="fa"></i> 预约项目</label>\
                        <label class="cr-styled m-l-20"><input type="radio" name="project-type'+k+'" '+(v.SubscribeType == 100 ? 'checked':'')+' class="SubscribeObj" value="2"><i class="fa"></i> 预约人员</label>\
                        </div>\
                    </div>\
                    <label class="col-md-3 control-label pass-msg error" style="font-weight: 500;"></label>\
                </div>\
                <div class="form-group overflow">\
                <label class="col-md-2 control-label padleft17 ObjName" style="font-weight: 500;">'+(v.SubscribeType == 200 ? '项目':'人员')+'名称：</label>\
                <div class="col-md-3">\
                <input type="text" class="form-control p-yl6 objname" data-pid="'+(k+1)+'" placeholder="" value="'+v.SubscribeObjName+'">\
                </div>\
                <div class="col-md-4">\
                <div class="input-group AppointmentImg" style="display: '+(isimg ? '':'none')+'">\
                    <input type="text" id="example-input2-group1" name="example-input2-group1" class="form-control profileupload" data-pid="'+(k+1)+'" readonly="" value="'+(isimg?sales.GetUrlRelativePath(v.SubscribeObjSrc):'')+'">\
                        <span class="input-group-addon"><i class="fa ion-image"></i></span>\
                    </div>\
                </div>\
                <label class="col-md-3 control-label pass-msg error" style="font-weight: 500;"></label>\
                </div>\
                <div class="form-group overflow">\
                <label class="col-md-2 control-label padleft17" style="font-weight: 500;">预约日期：</label>\
                <div class="col-md-3">\
                <div class="input-group">\
                    <input type="text" class="form-control startdate" placeholder="" id="StartDate'+(k+1)+'" readonly="" value="'+ m.formatYmd(v.StartDate)+'">\
                        <span class="input-group-addon"><i class="glyphicon ion-calendar"></i></span>\
                    </div>\
                </div>\
                <div class="col-md-1" style="text-align: center;height: 33px;line-height: 33px;">至</div>\
                <div class="col-md-3">\
                    <div class="input-group">\
                        <input type="text" class="form-control enddate" placeholder="" id="EndDate'+(k+1)+'" readonly="" value="'+ m.formatYmd(v.EndDate)+'">\
                            <span class="input-group-addon"><i class="glyphicon ion-calendar"></i></span>\
                        </div>\
                    </div>\
                    <label class="col-md-3 control-label pass-msg error usedate" style="font-weight: 500;"></label>\
                </div>\
                <div class="appsettime">';
                timestr += '<div class="date-list-item" style="display:'+(k== 0? 'block':'none')+'">\
                <div class="date-time">\
                <div class="buylen manage_per" style="margin-bottom: 0px;">\
                    <ul>\
                        <li class="handhover date">\
                            <p class="left">预约日期</p>\
                            <p class="right" style="position: relative;">\
                                <span class="StartDate1">'+ m.formatYmd(v.StartDate)+'</span> 至 <span class="EndDate1">'+ m.formatYmd(v.EndDate)+'</span>\
                                <span class="fa fa-angle-right" style="font-size: 22px;color: #7b7b7b;"></span>\
                            </p>\
                        </li>\
                        <li class="handhover time" style="">\
                            <p class="left">预约时间</p>\
                            <p class="right"></p>\
                        </li>\
                    </ul>\
                </div>\
                </div><div class="time-list pad4" style="">';
                if(istime){
                    $.each(v.SubscribeTimeList,function(key,val){
                        inputstr +='<div class="form-group overflow AppointmentSet">\
                    <label class="col-md-2 control-label padleft17 AppointmentTime '+(istime ? '':'hidden1')+'" style="font-weight: 500;"><span>时间'+(key+1)+'：</span></label>\
                    <div class="col-md-3 AppointmentTime '+(istime ? '':'hidden1')+'">\
                        <input type="text" class="form-control p-yl4 subscribetime" id="StartTime'+(k+1)+'-'+(key+1)+'" readonly value="'+(istime ? val.SubscribeTime :'')+'">\
                        </div>\
                        <div class="col-md-1 AppointmentCount '+(iscount ? '':'hidden1')+'" style="text-align: center;height: 33px;line-height: 33px;padding: 0px;"><span>数量</span></div>\
                        <div class="col-md-3 AppointmentCount  '+(iscount ? '':'hidden1')+'">\
                            <input type="number" class="form-control p-yl4 count" data-classname="count" value="'+(iscount ? val.SubscribeCount:'')+'">\
                            </div>\
                            <div class="col-md-3 control-label" style="font-weight: 500;">\
                                <p class="addTime"><i class="ion-plus"></i></p>\
                            </div>\
                        </div>';
                        timestr += '<span class="time-items">'+(istime ? val.SubscribeTime : '')+'</span>';
                    });
                }else{
                    console.log(iscount);
                    inputstr +='<div class="form-group overflow AppointmentSet">\
                    <label class="col-md-2 control-label padleft17 AppointmentTime '+(istime ? '':'hidden1')+'" style="font-weight: 500;"><span>时间1：</span></label>\
                    <div class="col-md-3 AppointmentTime '+(istime ? '':'hidden1')+'">\
                        <input type="text" class="form-control p-yl4 subscribetime" id="StartTime1-1" readonly ">\
                        </div>\
                        <div class="col-md-1 AppointmentCount '+(iscount ? '':'hidden1')+'" style="text-align: center;height: 33px;line-height: 33px;padding: 0px;"><span>数量</span></div>\
                        <div class="col-md-3 AppointmentCount  '+(iscount ? '':'hidden1')+'">\
                            <input type="number" class="form-control p-yl4 count" data-classname="count" value="">\
                            </div>\
                            <div class="col-md-3 control-label" style="font-weight: 500;">\
                                <p class="addTime"><i class="ion-plus"></i></p>\
                            </div>\
                        </div>';
                    timestr += '<span class="time-items"></span>';
                }

                    inputstr +='</div></div>';
                timestr += '</div></div>';
                numberstr +='<li class="project-item '+(k == 0 ? 'active' : '')+'"><span>'+ (k+1) +'</span></li>';
                textstr += '<li class="name '+( k == 0 ? 'active': '')+' promote-protext1">'+ v.SubscribeObjName +'</li>';
                imgstr += '<div class="item active appa-list-item">\
                <p class="img promote-proimg'+(k+1)+'">\
                <img src="'+ v.SubscribeObjSrc+'" onerror="this.src=\'/modules/img/default.jpg\'"></p>\
                <p class="name onetexthide  promote-protext1">'+ v.SubscribeObjName+'</p>\
                </div>';
            });

            $(".projectcont-list").html(inputstr);
            $(".project-list-list").html(numberstr);
            $(".date-list-wrap").html(timestr);
            $(".show-text-list").html(textstr);
            $(".owl-example-list").html(imgstr);
            if(data.length > 1){
                sales.loaded();
            }else{
                $("#owl-example").html(imgstr);
            }

            $.each(data,function(k,v){
                sales.datetime(k+1);
                if(istime){
                    $.each(v.SubscribeTimeList,function(key,val){
                        sales.timeslot(k+1,key+1);
                    });
                }

            });
            if(!istime){
                sales.timeslot(1,1);
                $(".appsettime").addClass("hiden");
                if(!iscount){
                    $(".appsettime").find(".form-group").hide();
                }
            }
            sales.projectindex = data.length + 1;

            if(!istime){
                $(".manage_per .time").hide();
                $(".time-list").hide();
            }

        },
        //剪切图片
        cropperImg:function(){
            var options =
            {
                imageBox: '.imageBox',
                thumbBox: '.thumbBox',
                spinner: '.spinner',
            }
            var cropper = '';
            document.querySelector('#MainSrc').addEventListener('change', function(){
                var MyTest = document.getElementById("#MainSrc");
                var _this = this;

                var reader = new FileReader();
                reader.onload = function(e) {
                    options.imgSrc = e.target.result;
                    var image = new Image();
                    image.src = e.target.result;
                    image.onload = function() {
                        if(image.width < 700 || image.height < 400){
                            layer.msg("图片尺寸必须大于700*400");
                            return false;
                        }else{
                            bytesupload(options.imgSrc);
                            return false;
                        }
                        //if(image.width == 700 && image.height == 400){
                        //
                        //}else{
                        //    cropper = new cropbox(options);
                        //    $("#CutImg").modal('show');
                        //}
                    };
                }
                reader.readAsDataURL(this.files[0]);
            })
            document.querySelector('#btnCrop').addEventListener('click', function(){
                var img = cropper.getDataURL();
                bytesupload(img);
            })

            var bytesupload = function(base){
                $.ajax({
                    type: "POST",
                    url: "/promote/get-bytes-by-image-path",
                    data : {baseImg:base},
                    dataType: "json",
                    success: function (ret){
                        if(ret.IsBizSuccess){
                            $(".MainSrc").attr("src",ret.ImgSrc);
                            $("#MainSrc").next(".input-group").find("input").val(ret.ImgSrc);
                            sales.ImgSrc = ret.FileName;
                            $("#CutImg").modal('hide');
                        }else{
                            layer.msg("图片上传失败，请重新上传！");
                        }
                    }
                });
            }
        },
        //上传图片
        ajaxUpload:function(){
            var adid = 0;
            var pid = 1;
            var obj = '';
            var uptype = 1;
            $(document).on("click", ".fileupload", function(){
                $("#file").click();
                adid = $(this).attr("data-adid");
                obj = $(this);
                uptype = 1;
            });
            $(document).on("click", ".profileupload", function(){
                $("#file").click();
                pid = $(this).attr("data-pid");
                obj = $(this);
                uptype = 2;
            });

            //图片上传
            $("#file").on("change",function () {
                ajaxFileUpload();
            });
            function ajaxFileUpload(){
                $.ajaxFileUpload({
                    url:m.baseUrl+"/customer/edit-head",
                    secureuri: false,
                    fileElementId: 'file',
                    dataType: 'json',
                    success: function (ret) {
                        if(ret.IsBizSuccess){
                            if(uptype == 1){
                                obj.val(ret.Photo);
                                $(".promote-cont"+adid).find("img").attr('src',ret.Photo);
                            }else{
                                obj.val(ret.FileName);
                                $(".ShowImg").find(".promote-proimg"+pid).find("img").attr('src',ret.Photo);
                                $(".owl-example-list").find(".promote-proimg"+pid).find("img").attr('src',ret.Photo);
                            }

                        }else{
                            layer.msg(ret.ErrMsg);
                            return false;
                        }
                    }
                })
                return false;
            }
        },
        //日期
        datetime:function(i){
            //初始化日期控件
            function setEndTime(enddate){
                $('#StartDate'+i).datetimepicker('remove');
                $('#StartDate'+i).datetimepicker({
                    format:'yyyy-mm-dd',
                    language:  'zh-CN',
                    minView: "month",
                    autoclose: 1,
                    todayHighlight: 1,
                    startView: 2,
                    forceParse: 0,
                    'startDate':new Date(),
                    'endDate':sales.transferDate(enddate)
                });
            }
            function transferTime(str){
                var newstr=str.replace(/-/g,'-');
                var newdate=new Date(newstr);
                var time=newdate.getTime();
                return time;
            }
            //结束时间戳和开始时间戳比较
            function checkTime(start,end){
                if(end <= start){
                    return true;
                }
                return false;
            }
            $('#StartDate'+i).datetimepicker({
                format:'yyyy-mm-dd',
                language:'zh-CN',
                minView: "month",
                autoclose: true,
                'startDate':new Date()
            }).on("changeDate",function(ev){
                sales.getDateRange();
                var transferdate = sales.transferDate($("#StartDate"+i).val());//转时间日期
                var str =  $("#StartDate"+i).val();
                var newstr = str.split('-');
                var datestr = newstr[0]+'年' + newstr[1]+ '月' +newstr[2]+ '日'
                $(".StartDate"+i).html(str);
                var newtime = new Date();
                $('#EndDate'+i).datetimepicker('remove');
                $('#EndDate'+i).datetimepicker({
                    format:'yyyy-mm-dd ',
                    language:'zh-CN',
                    minView: "month",
                    autoclose:true,
                    'startDate':transferdate < newtime ? newtime :transferdate
                }).on("changeDate",function(ev){
                    sales.getDateRange();
                    var enddate=$("#EndDate"+i).val();
                    var newstr = enddate.split('-');
                    var datestr = newstr[0]+'年' + newstr[1]+ '月' +newstr[2]+ '日'
                    $(".EndDate"+i).html(enddate);
                    setEndTime(enddate);
                });
            });
            $('#EndDate'+i).datetimepicker({
                format:'yyyy-mm-dd',
                language:'zh-CN',
                minView: "month",
                'startDate':new Date(),
                autoclose:true
            }).on("changeDate",function(ev){
                sales.getDateRange();
                var enddate=$("#EndDate"+i).val();
                var newstr = enddate.split('-');
                var datestr = newstr[0]+'年' + newstr[1]+ '月' +newstr[2]+ '日'
                $(".EndDate"+i).html(enddate);
                setEndTime(enddate);
            });
        },
        timeslot:function(i,j){
            $('#StartTime'+i+'-'+j).datetimepicker({
                language:'zh-CN',
                format: "hh:ii",
                startView:1,
                maxView:1,
                minuteStep:10,
                autoclose: true
            }).on("changeDate",function(ev){
                sales.getDateRange();
                setTimeout(function(){
                    var time = $('#StartTime'+i+'-'+j).val();
                    $(".time-list").eq(i-1).find(".time-items").eq(j-1).html(time);
                },1);
            });
        },
        getDateRange:function(){
            var MinDate = '';
            var MaxDate = '';
            $(".projectcont-item").each(function(k,v){
                var startDate = $(this).find(".startdate").val();
                var endDate = $(this).find(".enddate").val();
                if(startDate.length > 0){
                    startDate = sales.transferDate(startDate);
                    if(MinDate.length < 1){
                        MinDate = startDate;
                    }else{
                        if(startDate < MinDate){
                            MinDate = startDate;
                        }
                    }
                }
                if(endDate.length > 0){
                    endDate = sales.transferDate(endDate);
                    if(MaxDate.length < 1){
                        MaxDate = endDate;
                    }else{
                        if(endDate > MaxDate){
                            MaxDate = endDate;
                        }
                    }
                }

            });
            $(".ActStartTime").html('<span class="ion-ios7-clock"></span>'+(MinDate ? m.formatYmdtext1(MinDate):'2017年6月27日')+' 至 '+(MaxDate ? m.formatYmdtext1(MaxDate):'2017年6月30日'));
        },
        //文本编辑器
        editor:'',
        simditor:function(){
            sales.editor = new Simditor({textarea:$("#editor"),toolbar:false});
            sales.editor.on('valuechanged',function(){
                $("#ShowMessage .Notice").html(sales.editor.getValue());
            });
        },
        getCont:function(){
            var adContent = '';
            $(".promote-scendcon").find(".col-md-7").each(function(k){
                var str  = '';
                if($(this).find("textarea").length){
                    var value  = $(this).find("textarea").val().trim();
                    if(value.length > 1){
                        str += '<p class="promote-cont'+k+'">'+value+'</p>';
                    }
                }else if($(this).find(".fileupload").length){
                    var value  = $(this).find(".fileupload").val().trim();
                    if(value.length > 1){
                        str += '<p class="promote-cont'+k+'"><img src="'+ value +'"></p>';
                    }
                }
                adContent += str;
            });
            return adContent;
        },
        //错误处理
        errorMessage:function(str,classname,errmsg){
            if(str.length < 1){
                var html = $(".pass-msg."+classname).html();
                if(html.length < 1){
                    $(".pass-msg."+classname).html(errmsg);
                }
                return false;
            }else{
                $(".pass-msg."+classname).html("");
                return true
            }
        },
        //添加段落
        addStr:function(addtype){
            if(addtype == 'img'){
                var str = '<div class="form-group overflow">\
                <label class="col-md-2 control-label padleft17" style="font-weight: 500;">展示图片：</label>\
                <div class="col-md-7 promote-chosetupload">\
                        <div class="input-group">\
                            <input type="text" id="example-input2-group1" name="example-input2-group1" class="form-control fileupload"  data-adid="'+sales.adid+'" readonly="">\
                                <span class="input-group-addon"><i class="fa ion-image"></i></span>\
                            </div>\
                        </div>\
                        <div class="col-md-3 add-promote-btnlist">\
                            <ul class="p-ul5 p-ul7">\
                                <li class="add-img"  data-adid="'+sales.adid+'"><span class="ion-image"></span></li>\
                                <li class="add-font" data-adid="'+sales.adid+'"><span class="fa fa-font" style="font-size: 23px;"></span></li>\
                                <li class="del-btn"  data-adid="'+sales.adid+'"><span class="fa fa-trash-o"></span></li>\
                                <div class="clear"></div>\
                            </ul>\
                        </div>\
                    </div>';
                var str1 = '<p class="promote-cont'+sales.adid+'"><img src="/modules/img/default.jpg"></p>';
            }else if(addtype == 'font') {
                var str = '<div class="form-group overflow">\
                    <label class="col-md-2 control-label padleft17" style="font-weight: 500;">文字说明：</label>\
                    <div class="col-md-7">\
                        <textarea class="form-control p-yl3"  data-adid="' + sales.adid + '"></textarea>\
                    </div>\
                    <div class="col-md-3 add-promote-btnlist">\
                        <ul class="p-ul5 p-ul7">\
                            <li class="add-img" data-adid="' + sales.adid + '"><span class="ion-image"></span></li>\
                            <li class="add-font" data-adid="' + sales.adid + '"><span class="fa fa-font" style="font-size: 23px;"></span></li>\
                            <li class="del-btn"   data-adid="' + sales.adid + '"><span class="fa fa-trash-o"></span></li>\
                            <div class="clear"></div>\
                        </ul>\
                    </div>\
                </div>';
                var str1 = '<p class="promote-cont'+sales.adid+'"></p>';
            }
            sales.adid ++;
            return [str,str1];
        },

        //将时间字符串转为date
        transferDate:function(data){
            var start_time = data;
            var newTime= start_time.replace(/-/g,"-");
            var transferdate = new Date(newTime);
            return transferdate;
        },
        //去除域名获取相对路径
        GetUrlRelativePath:function(url){
            var arrUrl = url.split("//");
            var length = arrUrl.length;
            if(length > 1){
                var start = arrUrl[length-1].indexOf("/");
                var relUrl = arrUrl[length-1].substring(start);//stop省略，截取从start开始到结尾的所有字符
                if(relUrl.indexOf("?") != -1){
                    relUrl = relUrl.split("?")[0];
                }
                return relUrl;
            }else{
                return url;
            }
        }
    }
    sales._init();

})